package com.geen.tuoke.ui.fragment

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.module.LoadMoreModule
import com.geen.tuoke.MyApplication
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseAdapter
import com.geen.tuoke.base.BaseFragment
import com.geen.tuoke.bean.CustomerInfo
import com.geen.tuoke.bean.Label
import com.geen.tuoke.databinding.FragmentHomeBinding
import com.geen.tuoke.databinding.ItemCustomListBinding
import com.geen.tuoke.databinding.ItemCustomerLabelBinding
import com.geen.tuoke.ui.activity.AddLabelActivity
import com.geen.tuoke.ui.activity.AddOrEditCustomerActivity
import com.geen.tuoke.ui.activity.SearchCustomerActivity
import com.geen.tuoke.ui.popupwindow.CustomerFuncPopup
import com.geen.tuoke.ui.viewmodel.CustomerViewModel
import com.geen.tuoke.ui.viewmodel.MainViewModel
import com.geen.tuoke.utils.ext.dp2px
import com.geen.tuoke.utils.ext.startActivity
import com.geen.tuoke.widget.CustomLoadMoreView
import com.geen.tuoke.widget.EmptyLayout
import com.qmuiteam.qmui.kotlin.onClick
import com.yqritc.recyclerviewflexibledivider.VerticalDividerItemDecoration

/**
 * @Author LuoJi
 * @Date 2021/12/23-15:27
 * @Desc
 */
class FragmentHome : BaseFragment<CustomerViewModel, FragmentHomeBinding>() {
    lateinit var adapter: BaseAdapter<CustomerInfo, ItemCustomListBinding>
    private val mainViewModel by activityViewModels<MainViewModel>()
    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.run {
            adapter = object : BaseAdapter<CustomerInfo, ItemCustomListBinding>(
                R.layout.item_custom_list
            ),LoadMoreModule {
                override fun onUpdate(
                    binding: ItemCustomListBinding,
                    item: CustomerInfo,
                    position: Int
                ) {
                    binding.run {
                        data = item

                        loadLabelListUi(this, context, item)

                        ivMore.onClick {
                            CustomerFuncPopup(activity!!, {
                                openWx(item.mobile)
                            }, {
                                AddLabelActivity.start(context, item)
                            }, {
                                AddOrEditCustomerActivity.start(
                                    ivMore.context,
                                    item
                                )
                            }).createPopup<CustomerFuncPopup>()
                                .showAsDropDown(
                                    ivMore, -dp2px(125f), -dp2px(60f)
                                )

                        }
                    }
                }
            }
            rv.adapter = adapter

            adapter.setEmptyView(EmptyLayout(requireContext()))

            ivAddCustomer.onClick {
                AddOrEditCustomerActivity.start(ivAddCustomer.context, null)
            }

            // 处理分页
            adapter.loadMoreModule.loadMoreView = CustomLoadMoreView()
            adapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
            adapter.loadMoreModule.isEnableLoadMore = true
            adapter.loadMoreModule.isAutoLoadMore = true

            adapter.loadMoreModule.setOnLoadMoreListener {
                mViewModel.getCustomerList(false)
            }

            etSearch.setOnClickListener {
                //跳转到一个新的搜索界面
                startActivity<SearchCustomerActivity>()
            }
        }

        mBinding.swipeRefresh.setOnRefreshListener {
            mViewModel.pageNo = 1
            mViewModel.getCustomerList(false)
        }

        mainViewModel.tabHomeRestart.observe(viewLifecycleOwner,{
            if(it){
                mViewModel.pageNo = 1
                mViewModel.getCustomerList(true)
            }
        })

        mBinding.swipeRefresh.setColorSchemeColors(
            ContextCompat.getColor(
                requireContext(),
                R.color.colorPrimary
            )
        )
    }

    private fun loadLabelListUi(
        itemCustomListBinding: ItemCustomListBinding,
        context: Context,
        item: CustomerInfo
    ) {

        itemCustomListBinding.rvLabel.isVisible = item.labels.isNotEmpty()

        itemCustomListBinding.rvLabel.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        itemCustomListBinding.rvLabel.adapter =
            object : BaseAdapter<Label, ItemCustomerLabelBinding>(
                R.layout.item_customer_label,
                item.labels.toMutableList()
            ) {
                override fun onUpdate(
                    binding: ItemCustomerLabelBinding,
                    item: Label,
                    position: Int
                ) {
                    binding.tvLabel.text = item.name
                }

                override fun getItemCount(): Int {
                    //防止标签太多 这里先限制3个
                    return if (super.getItemCount() > 3) 3 else super.getItemCount()
                }
            }
    }

    private fun openWx(item: String) {
        ClipboardUtils.copyText(item)
        try {
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.component = MyApplication.instance.getPackageManager()
                .getLaunchIntentForPackage("com.tencent.mm")?.component
            startActivity(intent)
        } catch (e: Exception) {
            ToastUtils.showShort("设备无微信")
            e.printStackTrace()
        }
    }

    override fun initData() {
        super.initData()
        mViewModel.customerList.observe(this) {
            if (mViewModel.pageNo == 1) {
                adapter.setList(it)
            } else {
                adapter.addData(it)
            }
            if (mViewModel.pageNo == mViewModel.totalPage) {
                adapter.loadMoreModule.loadMoreEnd()
            } else {
                adapter.loadMoreModule.loadMoreComplete()
            }
            mViewModel.pageNo++
            mBinding.swipeRefresh.isRefreshing = false
        }
    }

    override fun onLazyLoad() {
        mViewModel.getCustomerList()

    }

    override fun onResume() {
        super.onResume()
    }

}